package com.rc.saas.tenant.controller.tenant;

import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.tenant.TenantSettingMapper;
import com.rc.saas.tenant.model.tenant.TenantSetting;
import com.rc.saas.tenant.model.tenant.TenantSettingExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.elec.ElecGunService;
import com.rc.saas.tenant.service.elec.ElecPileService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.msg.TenantCustomMsgService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.tenant.MemberCountVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author frog
 * @date 2021/6/1
 */
@Controller
@RequestMapping(value = "/statistics")
public class StatisticsController {

    private static Logger logger = LogManager.getLogger(StatisticsController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    @Autowired
    private TenantCustomMsgService tenantCustomMsgService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private TenantSettingMapper tenantSettingMapper;

    /**
     * 跳控制台(统计)页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String statisticsPage() {
        return "/templates/tenant/statistics/statistics";
    }


    /**
     * 未读客服消息，企业账号申请，会员数，新增会员数。
     */
    @RequestMapping(value = "/selectStatistics", method = RequestMethod.GET)
    @ResponseBody
    public TResponse findStatistics() {
        try {
            TenantUser user = ShiroUtils.getSessionUser();

            MemberCountVo memberCountVo = new MemberCountVo();

            // 会员数
            long allCount = memberInfoService.countAllMember(user.getTenantCode());
            memberCountVo.setAllCount(allCount);

            // 今天新增会员数
            long newAddCount = memberInfoService.countTodayNewAdd(user.getTenantCode());
            memberCountVo.setNewAddCount(newAddCount);

            // 企业账号申请
            long applyCount = enterpriseMemberApplyService.countAllApply(user.getTenantCode());
            memberCountVo.setApplyCount(applyCount);

            // 未读客服消息
            long unreadMsgCount = tenantCustomMsgService.countUnreadMsg(user.getTenantCode());
            memberCountVo.setUnreadMsgCount(unreadMsgCount);

            //总功率
            BigDecimal totalPowerByStation = elecPileService.sumTotalPowerByEpg(user.getTenantCode());
            memberCountVo.setTotalPowerByStation(totalPowerByStation);

            //在线桩
            long loginPileCount = elecPileService.countLoginPile(user.getTenantCode());
            memberCountVo.setLoginPileCount(loginPileCount);

            //枪使用
            long useGuncount = elecGunService.countUseGun(user.getTenantCode());
            memberCountVo.setUseGuncount(useGuncount);

            //充电桩总数
            // 0 : 直流桩  1 :交流桩  2:交直流一体
            long pileCount = elecPileService.countPile(user.getTenantCode(), null);
            memberCountVo.setPileCount(pileCount);

            //充电枪总数
            long guncount = elecGunService.countGun(user.getTenantCode());
            memberCountVo.setGuncount(guncount);

            // 直流桩数
            long directCurrentPileCount = elecPileService.countPile(user.getTenantCode(), "0");
            memberCountVo.setDirectCurrentPileCount(directCurrentPileCount);

            // 交流桩数
            long exchangePileCount = elecPileService.countPile(user.getTenantCode(), "1");
            memberCountVo.setExchangePileCount(exchangePileCount);

            // 直交一体桩数
            long directCurrentAndExchangePileCount = elecPileService.countPile(user.getTenantCode(), "2");
            memberCountVo.setDirectCurrentAndExchangePileCount(directCurrentAndExchangePileCount);
            //桩在线率
            BigDecimal pileOnlineRate = new BigDecimal(0);
            if (pileCount == 0) {
                pileOnlineRate = new BigDecimal(0);
            } else if (loginPileCount == 0) {
                pileOnlineRate = new BigDecimal(1);
            } else {
                pileOnlineRate = new BigDecimal(loginPileCount).divide(new BigDecimal(pileCount), 2, BigDecimal.ROUND_HALF_UP);
            }

            memberCountVo.setPileOnlineRateVo(pileOnlineRate.multiply(new BigDecimal(100)).toString() + "%");
            memberCountVo.setPileOnlineRate(pileOnlineRate);

            TenantSettingExample example = new TenantSettingExample();
            example.createCriteria().andTenantCodeEqualTo(user.getTenantCode());
            List<TenantSetting> tenantSettings = tenantSettingMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(tenantSettings)) {
                TenantSetting tenantSetting = tenantSettings.get(0);
                memberCountVo.setPileOnlineWarnValue(tenantSetting.getPileOnlineWarnValue());
                memberCountVo.setPileOnlineWarnMobiles(tenantSetting.getPileOnlineWarnMobiles());
                memberCountVo.setOpenPileOnlineWarn(tenantSetting.getOpenPileOnlineWarn());
            }

            return TResponse.SUCCESS_DATA(memberCountVo);
        } catch (Exception e) {
            logger.error("查询控制台失败", e);
        }
        return TResponse.FAIL();
    }


    /**
     * 保存桩在线率短信提醒
     *
     * @return
     */
    @RequestMapping(value = "/savePileWarn", method = RequestMethod.POST)
    @ResponseBody
    public TResponse savePileWarn(TenantSetting tenantSetting) {
        try {

            if (!BeanUtil.isValid(tenantSetting.getOpenPileOnlineWarn(), tenantSetting.getPileOnlineWarnValue(),
                    tenantSetting.getPileOnlineWarnMobiles())) {
                return TResponse.FAIL("请输入正确的参数");
            }

            if (tenantSetting.getPileOnlineWarnValue() > 100 || tenantSetting.getPileOnlineWarnValue() < 0) {
                return TResponse.FAIL("请输入不大于100并小于0的数字");
            }
            TenantUser sessionUser = ShiroUtils.getSessionUser();
            TenantSettingExample example = new TenantSettingExample();
            example.createCriteria().andTenantCodeEqualTo(sessionUser.getTenantCode());
            List<TenantSetting> tenantSettings = tenantSettingMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(tenantSettings)) {
                if (tenantSettings.size() > 1) {
                    return TResponse.FAIL("存在多个运营商");
                }

                String[] mobiles = tenantSetting.getPileOnlineWarnMobiles().split(",");
                for (String mobile : mobiles) {
                    if (mobile.length() != 11) {
                        return TResponse.FAIL("提示：手机号不存在或手机号未按英文逗号隔开输入！");
                    }
                }
                TenantSetting setting = tenantSettings.get(0);
                if (tenantSetting.getPileOnlineWarnMobiles().length() > 120) {
                    return TResponse.FAIL("最多可保存十个手机号");
                }
                setting.setOpenPileOnlineWarn(tenantSetting.getOpenPileOnlineWarn());
                setting.setPileOnlineWarnMobiles(tenantSetting.getPileOnlineWarnMobiles());
                setting.setPileOnlineWarnValue(tenantSetting.getPileOnlineWarnValue());
                tenantSettingMapper.updateByPrimaryKeySelective(setting);
            } else {
                return TResponse.FAIL("没有此运营商");
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存桩在线率短信提醒失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

}
